import { httpBatchLink, createTRPCClient } from '@trpc/client'
import { createServerSideHelpers } from '@trpc/react-query/server'
import { createTRPCNext } from '@trpc/next'
import type { AppRouter } from '../trpc/routes/_app'
import superjson from 'superjson'

function getBaseUrl() {
  if (typeof window !== 'undefined') return ''
  if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`
  if (process.env.RENDER_INTERNAL_HOSTNAME)
    return `http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}`
  return `http://localhost:${process.env.PORT ?? 3000}`
}

export const trpc = createTRPCNext<AppRouter>({
  transformer: superjson,
  config() {
    return {
      links: [
        httpBatchLink({
          url: `${getBaseUrl()}/api/trpc`,
          transformer: superjson,
          async headers() {
            return {
              'x-trpc-source': 'nextjs-react'
            }
          }
        })
      ]
    }
  },
  ssr: false
})
const proxyClient = createTRPCClient<AppRouter>({
  links: [
    httpBatchLink({
      url: `${getBaseUrl()}/api/trpc`,
      transformer: superjson
    })
  ]
})

export const helpers = createServerSideHelpers({
  client: proxyClient
})
